//
//  USMomentsDetailController.m
//  us
//
//  Created by karry on 2025/6/2.
//

#import "USMomentsDetailController.h"
#import "USMomentsAddController.h"
#import "USMomentCommentModel.h"
#import "USMomentsCell.h"
#import "USMomentCommentCell.h"
#import "USCommentInputToolView.h"
#import <MJRefresh/MJRefresh.h>
#import "USPhotoPreviewController.h"
@interface USMomentsDetailController ()<UITableViewDelegate,UITableViewDataSource,USMomentCommentDelegate>

@property (nonatomic, strong) NSMutableArray <USMomentCommentModel *>*list;
@property (nonatomic, strong) USCommentInputToolView *commentTool;
@end

@implementation USMomentsDetailController

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    
    // 注册键盘通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    

    if (self.momentModel) {
        [self.list addObjectsFromArray:[[self.momentModel.moodDiaryCommentList reverseObjectEnumerator] allObjects]];
        self.moodDiaryId = self.momentModel.moodDiaryDto.moodDiaryId;
        
        if ([self.momentModel.moodDiaryDto.userId isEqualToString: USUser.user.userId]) {
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"ic_more"] style:UIBarButtonItemStylePlain target:self action:@selector(editAction:)];
        }
    }else if (self.moodDiaryId.length > 0) {
        @weakify(self)
        [self requestMoodDiarySuccess:^{
         
            @strongify(self)
            if ([self.momentModel.moodDiaryDto.userId isEqualToString: USUser.user.userId]) {
                self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"ic_more"] style:UIBarButtonItemStylePlain target:self action:@selector(editAction:)];
            }
            
        }];
    }
    
    [self setupView];
    [self setupRefresh];
    
}

- (void)setupView{

    self.navigationItem.title = @"详情";
    
  
 
    
    self.us_tableView.delegate = self;
    self.us_tableView.dataSource = self;
    self.us_tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    self.us_tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.us_tableView.backgroundColor = UIColor.clearColor;
    self.us_tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag; // 滚动时自动收起键盘（可选）

    [self.us_tableView registerClass:[USMomentsCell class] forCellReuseIdentifier:@"USMomentsCell"];
    
    [self.us_tableView registerClass:[USMomentCommentCell class] forCellReuseIdentifier:@"USMomentCommentCell"];
    
    [self.view addSubview:self.commentTool];

}
- (void)setupRefresh {    
    @weakify(self)
    self.us_tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self)
        [self requestMoodDiarySuccess:^{
            
        }];
    }];
 
}
- (USCommentInputToolView *)commentTool {
    if (_commentTool == nil) {
        _commentTool = [[USCommentInputToolView alloc]initWithFrame:CGRectMake(0, self.view.bounds.size.height, self.view.bounds.size.width, 74)];
        _commentTool.hidden = YES;
        _commentTool.textField.placeholder = @"发表评论：";
        @weakify(self)
        _commentTool.onSend = ^(NSString *text) {
            @strongify(self)
            NSLog(@"发送内容: %@", text);
            [self.commentTool.textField resignFirstResponder];
            
            NSString *content = self.commentTool.textField.text?:@"";
            
            self.commentTool.textField.text = @"";
            [self sendComment:content];

        };
        
    }
    return _commentTool;
}

- (void)keyboardWillShow:(NSNotification *)notification {

    NSDictionary *info = notification.userInfo;
    NSTimeInterval duration = [info[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect kbFrame = [info[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyboardHeight = kbFrame.size.height;
    
    CGFloat toolHeight = 74;
    [UIView animateWithDuration:duration animations:^{
        self.commentTool.frame = CGRectMake(0, self.view.bounds.size.height - keyboardHeight - toolHeight, self.view.bounds.size.width, toolHeight);
        self.commentTool.hidden = NO;
    }];
   
    UIEdgeInsets insets = UIEdgeInsetsMake(0, 0, keyboardHeight + 74, 0);
    self.us_tableView.contentInset = insets;
    self.us_tableView.scrollIndicatorInsets = insets;
    [self.us_tableView jk_scrollToBottomAnimated:YES];

}

- (void)keyboardWillHide:(NSNotification *)notification {

    NSDictionary *info = notification.userInfo;
    NSTimeInterval duration = [info[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:duration animations:^{
        self.commentTool.frame = CGRectMake(0, self.view.bounds.size.height, self.view.bounds.size.width, 74);
    } completion:^(BOOL finished) {
        self.commentTool.hidden = YES;
    }];
    
    UIEdgeInsets insets = UIEdgeInsetsZero;
    self.us_tableView.contentInset = insets;
    self.us_tableView.scrollIndicatorInsets = insets;
}

- (NSMutableArray <USMomentCommentModel *>*)list {
    if (_list == nil) {
        _list = [NSMutableArray array];
    }
    return _list;
}
- (void)editAction:(UIBarButtonItem *)sender{

    @weakify(self)
    DTItem *item0 = [DTItem itemWithTitle:@"编辑" image:[UIImage imageNamed:@"icon-edit-22"] tag:0 identifier:nil handle:^(DTItem *item) {
        @strongify(self)
        [self editMomnt];
    }];
    
    DTItem *item1 = [DTItem itemWithTitle:@"删除" image:[UIImage imageNamed:@"icon-trash-22"] tag:0 identifier:nil handle:^(DTItem *item) {
        @strongify(self)
        [self deleteMomnt];
    }];

    DTTargetView *view = [DTTargetView initWithBarItem:sender item:@[item0,item1]];
    
    [view show];
    
}

- (void)editMomnt{
    USMomentsAddController *vc = [[USMomentsAddController alloc]init];
    vc.momentModel = self.momentModel;
    vc.isEdit = YES;
    
    @weakify(self)
    vc.editMomentBlock = ^(USMomentsModel * _Nonnull momntModel) {
     
        @strongify(self)
        dispatch_async(dispatch_get_main_queue(), ^{
            NSIndexPath *currentIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
            if (currentIndexPath) {
                NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:currentIndexPath.section];
                [self.us_tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
            }
        });
 
        if (self.editMomentBlock) {
            self.editMomentBlock();
        }
    };
     [self.navigationController presentViewController:[[DTNavigationController alloc]initWithRootViewController:vc] animated:YES completion:nil];

}
- (void)deleteMomnt{
    
    MOAlertBaseView *alert = [[MOAlertBaseView alloc]initWithTitle:@"确定删除此记录吗" detailTitle:@"此操作不可撤销哦，请谨慎操作" contentView:nil leftButtonImageName:nil rightButtonImageName:nil autoDissmiss:YES tapDissmiss:YES];
    alert.titleLabel.textColor = UIColor.us_redColor;
    @weakify(self)
    alert.didClickIndexBlock = ^(NSInteger index) {
        @strongify(self)
        if (index == 1) {
            [self deleteMomentRequest];
        }
    };
    
    [alert show];
    
}
#pragma mark - Net
- (void)requestMoodDiarySuccess:(void(^)(void))success {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
 
    params[@"moodDiaryId"] = self.moodDiaryId?:@"";
 
    [[EMNetWork shareManager] em_post:MoodDiaryView
                               params:params
                                  hud:nil
                           showError:YES
                              success:^(EMApiModel *api) {

        if (!api.success) {
            return;
        }
        
     
        USMomentsModel *diaryModel = [USMomentsModel mj_objectWithKeyValues:api.data[@"totalMoodDiary"]];
        
        self.momentModel = diaryModel;

        [self.list removeAllObjects];
        [self.list addObjectsFromArray:[[self.momentModel.moodDiaryCommentList reverseObjectEnumerator] allObjects]];
    
        if (self.editCommentBlock) {
            self.editCommentBlock();
        }
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            success();

            [self.us_tableView.mj_header endRefreshing];
            [self.us_tableView.mj_footer endRefreshing];
            
            [self.us_tableView reloadData];

        });
    } fail:^{
        
 
    }];
    
}
- (void)deleteMomentRequest {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    params[@"moodDiaryId"] = self.moodDiaryId?:@"";
  
    [[EMNetWork shareManager] em_post:MoodDiaryDelete
                               params:params
                                  hud:nil
                           showError:YES
                              success:^(EMApiModel *api) {

        if (!api.success) {
            return;
        }
        if (self.deleteMomentBlock) {
            self.deleteMomentBlock();
        }
        [USFeedbackTool notifySuccess];
        [self.navigationController popViewControllerAnimated:YES];
        
    } fail:^{
        
 
    }];
    
}

/// 添加评论
/// - Parameters:
///   - content: 内容
- (void)sendComment:(NSString *)content{
 
    NSDictionary *params = @{ @"content": content,
                              @"moodDiaryId": self.moodDiaryId?:@"",
    };

    @weakify(self)
    [[EMNetWork shareManager] em_post:MoodDiaryCommentAdd
                               params:params
                                  hud:nil
                            showError:NO
                              success:^(EMApiModel *api) {
        @strongify(self)
        if (!api.success) {
            return;
        }
        
        //最后插入数据
        USMomentCommentModel *model = [USMomentCommentModel mj_objectWithKeyValues:api.data[@"moodDiaryComment"]];
       
        [self.list insertObject:model atIndex:0];
        self.momentModel.moodDiaryCommentList = self.list;

        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.us_tableView beginUpdates];
            [self.us_tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            [self.us_tableView endUpdates];
            
            [self.us_tableView layoutIfNeeded];
        });
        
        if (self.editCommentBlock) {
            self.editCommentBlock();
        }
        
    } fail:^{
        
        
    }];
}
/// 删除评论
- (void)deleteComment:(USMomentCommentModel *)model{
 
    NSDictionary *params = @{ @"moodDiaryCommentId": model.moodDiaryCommentId,
                              @"moodDiaryId": self.moodDiaryId?:@"",
    };

    @weakify(self)
    [[EMNetWork shareManager] em_post:MoodDiaryCommentDelete
                               params:params
                                  hud:nil
                            showError:NO
                              success:^(EMApiModel *api) {
        @strongify(self)
        if (!api.success) {
            return;
        }
       
        dispatch_async(dispatch_get_main_queue(), ^{
            NSIndexPath *currentIndexPath = [self.list indexOfObject:model] != NSNotFound ? [NSIndexPath indexPathForRow:[self.list indexOfObject:model] inSection:1] : nil;
            if (currentIndexPath) {
                [self.list removeObjectAtIndex:currentIndexPath.row];
                self.momentModel.moodDiaryCommentList = self.list;
                [self.us_tableView deleteRowsAtIndexPaths:@[currentIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            }
            
            if (self.editCommentBlock) {
                self.editCommentBlock();
            }
        });
        
       
    } fail:^{
        
        
    }];
}

#pragma mark - USMomentCommentDelegate
- (void)commentCellDidLongPress:(USMomentCommentCell *)aCell bubbleView:(UIView *)bubbleView {
    [USFeedbackTool impactMedium];
    
    USMomentCommentModel *model = aCell.model;
 
    DTItem *copy = [DTItem itemWithTitle:@"复制" image:[UIImage imageNamed:@"icon_copy"] tag:0 identifier:nil handle:^(DTItem *item) {
        [self menuCopyMessage:model];
    }];
    
    DTItem *delete = [DTItem itemWithTitle:@"删除" image:[UIImage imageNamed:@"icon-trash-22"] tag:0 identifier:nil handle:^(DTItem *item) {
        
        [self deleteComment:model];
    }];
  
    NSArray *arr = @[copy];
    if ([model.userId isEqualToString:USUser.user.userId]) {
        arr = @[copy,delete];
    }
    
    DTTargetView *targetView = [[DTTargetView alloc]initWithTargetView:bubbleView item:arr];
    
    [targetView show];
    

}
- (void)menuCopyMessage:(USMomentCommentModel *)model{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = model.content;
}

#pragma mark - UITableViewDelegate
 
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }
   return self.list.count;
}

 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    if (indexPath.section == 0) {
        USMomentsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"USMomentsCell"];
        
        cell.model = self.momentModel;
        cell.editBtn.hidden = YES;
        
        @weakify(self)
        cell.commentBlock = ^{
            @strongify(self)
            [USFeedbackTool impactSoft];
            self.commentTool.hidden = NO;
            [self.commentTool.textField becomeFirstResponder];
        };
        
        cell.photoPreviewBlock = ^(NSInteger index) {
            @strongify(self)
            USPhotoPreviewController *vc = [[USPhotoPreviewController alloc] init];
            vc.items = self.momentModel.photoList;
            vc.currentIndex = index;
            [self.navigationController presentViewController:vc animated:YES completion:nil];

        };
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }else{
        USMomentCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"USMomentCommentCell"];
        cell.model = self.list[indexPath.row];
        cell.lineView.hidden = indexPath.row == self.list.count - 1? YES:NO;
        cell.delegate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
  
}

//-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
//    if (indexPath.section == 1) {
//        USMomentCommentCell *commentCell = (USMomentCommentCell *)cell;
//
//        if (self.list.count == 1) {
//            [commentCell.bgView jk_setRoundedCorners:UIRectCornerAllCorners radius:14];
//        }else{
//            if (indexPath.row == 0) {
//                [commentCell.bgView jk_setRoundedCorners:UIRectCornerTopLeft|UIRectCornerTopRight radius:14];
//            }else if (indexPath.row == self.list.count - 1){
//                [commentCell.bgView jk_setRoundedCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight radius:14];
//            }else{
//                commentCell.bgView.layer.mask = nil;
//            }
//        }
//
//    }
//    
// 
//}



@end

